package me.leiusual.sharing.ui.home.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.storeindex.ProductLink
import me.leiusual.sharing.api.model.storeindex.StoreIndex

/**
 * Create by leiusual on 2018/7/24
 */
class HomeHomeAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

  private val dataSet = arrayListOf<Item>()

  private val recycledViewPool = RecyclerView.RecycledViewPool()

  override fun getItemCount(): Int {
    return dataSet.size
  }

  override fun getItemViewType(position: Int): Int {
    return dataSet[position].type
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    return when (viewType) {
      0 -> {
        val itemView = inflater.inflate(R.layout.view_holder_home_banner, parent, false)
        HomeBannerViewHolder(itemView)
      }
      else -> {
        val itemView = inflater.inflate(R.layout.view_holder_home_floor_grid, parent, false)
        HomeFloorGridViewHolder(itemView, recycledViewPool)
      }
    }
  }

  override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    val data = dataSet[position]
    when (holder) {
      is HomeBannerViewHolder -> holder.bind(data)
      is HomeFloorGridViewHolder -> holder.bind(data)
    }
  }

  fun submitList(home: StoreIndex) {
    dataSet.clear()
    if (home.bannerList != null && home.bannerList.isNotEmpty()) {
      dataSet.add(Item(0, "Banner", home.bannerList))
    }
    if (home.floorList != null && home.floorList.isNotEmpty()) {
      dataSet.addAll(home.floorList.map {
        // 这里限制一下最多显示数量
        val size = it.productLinks.size
        Item(1, it.title, it.productLinks.subList(0, if (size > 12) 12 else size))
      })
    }
    notifyDataSetChanged()
  }

  data class Item(val type: Int, val title: String, val dataSet: List<ProductLink>)
}